package br.ufpe.cin.rdfilter.gui;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.swing.WindowConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import br.ufpe.cin.rdfilter.feedback.*;

/**
 * 
 * @author Rafael
 */
public class FrameStatistics extends javax.swing.JFrame {
	private javax.swing.JButton btnOk;
	private javax.swing.JTextArea taStatistics;
	private javax.swing.JScrollPane jScrollPane1;

	private static final long serialVersionUID = 1L;

	// public Vector<Anotacao> vectorAnotacoes;
	public Vector<Feedback> vectorFeedback = new Vector<Feedback>();
	public Feedback feedback;
	int numQuery = 0;
	int numAnnotation = 0;
	int numTP = 0;
	int numFP = 0;
	int numFN = 0;
	int precision = 0;
	int recall = 0;
	int fmeasure = 0;

	public FrameStatistics() {
		initComponents();
		this.setTitle("Estatistics");
		this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		loadFeedback();
		fillTextArea();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */

	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {
		btnOk = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		taStatistics = new javax.swing.JTextArea();
		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		btnOk.setText("Ok");
		btnOk.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnOkActionPerformed(evt);
			}
		});
		taStatistics.setColumns(20);
		taStatistics.setEditable(false);
		taStatistics.setRows(5);
		jScrollPane1.setViewportView(taStatistics);
		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.TRAILING)
												.addComponent(
														jScrollPane1,
														javax.swing.GroupLayout.Alignment.LEADING,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														310, Short.MAX_VALUE)
												.addComponent(
														btnOk,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														62,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jScrollPane1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										244,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(btnOk)
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}// </editor-fold>

	public void fillTextArea() {
		for (int i = 0; i < vectorFeedback.size(); i++) {
			numTP = numTP + vectorFeedback.get(i).getTp();
			numFP = numFP + vectorFeedback.get(i).getFp();
			numFN = numFN + vectorFeedback.get(i).getFn();
		}
		taStatistics.append("Number of annotated result of queries: " + numQuery);
		taStatistics.append("\nNumber of annotations: " + numAnnotation);
		taStatistics.append("\nNumber de TP: " + numTP);
		taStatistics.append("\nNumber de FP: " + numFP);
		taStatistics.append("\nNumber de FN: " + numFN + "\n");

		for (int ind = 0; ind < vectorFeedback.size(); ind++) {
			taStatistics.append("\nQuery: "
					+ vectorFeedback.get(ind).getQuery());
			taStatistics.append("\nPrecision: "
					+ vectorFeedback.get(ind).getPrecision());
			taStatistics.append("\nRecall: "
					+ vectorFeedback.get(ind).getRecall());
			taStatistics.append("\nF-measure: "
					+ vectorFeedback.get(ind).getF_measure() + "\n");
		}
	}

	private void loadFeedback() {
		Vector<Annotation> result = new Vector<Annotation>();
		File fileFeedback = new File("feedback.xml");
		if (fileFeedback.exists()) {
			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db;
				db = dbf.newDocumentBuilder();
				Document doc;
				doc = db.parse(fileFeedback);
				Element consultas = doc.getDocumentElement();
				NodeList listQuery = consultas
						.getElementsByTagName("query");
				this.numQuery = listQuery.getLength();
				for (int i = 0; i < listQuery.getLength(); i++) {
					Element query = (Element) listQuery.item(i);
					String idQuery = query.getAttributeNode("id").getValue();
					NodeList feedbackList = query
							.getElementsByTagName("feedback");
					Element feedback = (Element) feedbackList.item(0);
					NodeList annotationList = feedback
							.getElementsByTagName("annotation");
					for (int j = 0; j < annotationList.getLength(); j++) {
						Element annotationE = (Element) annotationList.item(j);
						Annotation annotation = createAnnotation(annotationE);
						result.addElement(annotation);
					}
					numAnnotation += result.size();
					Feedback f = new Feedback(idQuery, result);
					vectorFeedback.addElement(f);
					result.clear();
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private Annotation createAnnotation(Element element) {
		Annotation annotation = new Annotation();
		Triple triple = new Triple();
		
		NodeList tripleList = element.getElementsByTagName("triple");
		Element tripleE = (Element) tripleList.item(0);
		
		NodeList subjectList = tripleE.getElementsByTagName("subject");
		Element subject = (Element) subjectList.item(0);
		triple.setSubject(subject.getFirstChild().getNodeValue());
		
		NodeList predicateList = tripleE.getElementsByTagName("predicate");
		Element predicate = (Element) predicateList.item(0);
		triple.setPredicate(predicate.getFirstChild().getNodeValue());

		NodeList objectList = tripleE.getElementsByTagName("object");
		Element object = (Element) objectList.item(0);
		triple.setSubject(object.getFirstChild().getNodeValue());

		annotation.setTriple(triple);

		NodeList idQueryList = element.getElementsByTagName("idQuery");
		Element idQuery = (Element) idQueryList.item(0);
		annotation.setIdQuery(idQuery.getFirstChild().getNodeName());

		NodeList evaluationList = element.getElementsByTagName("evaluation");
		Element evaluation = (Element) evaluationList.item(0);
		annotation.setType(evaluation.getFirstChild().getNodeValue());

		NodeList confidenceList = element.getElementsByTagName("confidence");
		Element confidence = (Element) confidenceList.item(0);
		annotation.setConfidence(confidence.getFirstChild().getNodeValue());

		return annotation;
	}

	private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
		this.dispose();
	}
}